package cn.wangzg.course1201;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * Time: 2020/5/1
 * Author: wangzhiguo
 * Description: 裁剪图片，形成一个动画效果
 */
public class MyViewImage extends View {
    private Bitmap mBitmap = null;
    private int limitLength = 0;     //
    private int width;
    private int height;
    private static final int CLIP_HEIGHT = 50;
    private Path mPath;
    private boolean status = HIDE;//显示还是隐藏的状态，最开始为HIDE
    private static final boolean SHOW = true;//显示图片
    private static final boolean HIDE = false;//隐藏图片
    private int clipWidth=120;
    public MyViewImage(Context context) {
        this(context, null);
        init();
    }

    public MyViewImage(Context context, AttributeSet attrs) {
        super(context, attrs);
        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.meinv);
        limitLength = width = mBitmap.getWidth();
        height = mBitmap.getHeight();
        init();
    }

    public MyViewImage(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        mPath=new Path();
        //先关闭硬件加速
        //setLayerType(LAYER_TYPE_SOFTWARE,null);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPath.reset();
        //  先画出裁剪区域
        int i = 0;
        while (i * CLIP_HEIGHT <= height) {//计算clip的区域
            if(i%2==0){
               //替换了Region.union方法
                mPath.addRect(new RectF(0,i*CLIP_HEIGHT,clipWidth,(i+1)*CLIP_HEIGHT),Path.Direction.CCW);
            }else{
                mPath.addRect(new RectF(width,i*CLIP_HEIGHT,width-clipWidth,(i+1)*CLIP_HEIGHT),Path.Direction.CCW);
            }
            i++;
        }

        //替换了canvas.clipRegion(region)
        canvas.clipPath(mPath);
        canvas.drawBitmap(mBitmap, 0, 0, new Paint());

        if (status == HIDE) {//如果此时是隐藏
            clipWidth -= 10;
            if(clipWidth <= 0)
                status=SHOW;
        } else {//如果此时是显示
            clipWidth += 5;
            if(clipWidth >= width)
                status=HIDE;
        }

        postInvalidate();//视图会在失效后重绘，即重新执行onDraw方法
    }
}
